import hashlib
import io
import os
import uuid

from BlackWhiteSite.settings import UPLOAD_FILES_DIRS


def to_md5_hex(data):
    """生成MD5摘要"""
    if type(data) != bytes:
        if type(data) == str:
            data = data.encode()
        elif type(data) == io.BytesIO:
            data = data.getvalue()
        else:
            data = bytes(data)
    return hashlib.sha256(data).hexdigest()


def upload_image_to_local(files):
    """将用户图片存到本地"""
    # 判断大小
    if files.size > 5 * 1024 * 1024:
        return "", False, "文件大小超过5M"
    # 准备文件名后缀
    file_ends = os.path.splitext(files.name)[1]
    if file_ends.upper() not in ['.PNG', '.JPG', '.JPEG', '.GIF']:
        return "", False, "文件类型不被允许 （png jpg jpeg gif）"
    content = files.read()
    file_name = to_md5_hex(content) + file_ends
    # 确定保存路径
    image_path = os.path.join(UPLOAD_FILES_DIRS, file_name)
    # 存入图片
    with open(image_path, 'wb') as f:
        f.write(content)
    return file_name, True, "存入成功"
